//
// Created by kyle on 25-7-15.
//

#ifndef FRAMEBUFFER_H
#define FRAMEBUFFER_H

#include <iostream>
#include <string>
#include <system_error>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/fb.h>

class FrameBuffer {
private:
    // 绘制四分之一圆 (辅助函数)
    void draw_circle_quarter(int x0, int y0, int radius,
                             uint8_t r, uint8_t g, uint8_t b, int quadrant);
    // 填充四分之一圆 (辅助函数)
    void fill_circle_quarter(int x0, int y0, int radius,
                           uint8_t r, uint8_t g, uint8_t b, int quadrant);

public:
    int fd = -1;
    struct fb_var_screeninfo var_info{};
    //屏幕宽度
    int width = 0;
    //屏幕高度
    int height = 0;
    int bpp = 0;
    int bytes_per_pixel = 0;
    size_t screen_size = 0;
    void *map = MAP_FAILED;
    void *back_buffer = nullptr;

    ~FrameBuffer() {
        if (back_buffer) {
            free(back_buffer);
            back_buffer = nullptr;
        }
        if (map != MAP_FAILED) {
            munmap(map, screen_size);
            map = MAP_FAILED;
        }
        if (fd >= 0) {
            close(fd);
            fd = -1;
        }
    }

    /**
     * 初始化缓冲区
     * @return
     */
    bool init();

    /**
     * 清空后备缓冲区
     * @param fb
     * @param r
     * @param g
     * @param b
     */
    void clear_back_buffer(uint8_t r, uint8_t g, uint8_t b);

    // 更新屏幕显示
    void update_screen();

    //画像素
    void write_pixel(int x, int y, uint8_t r, uint8_t g, uint8_t b);

    //画线
    void draw_line(int x0, int y0, int x1, int y1, uint8_t r, uint8_t g, uint8_t b);

    //画圆
    void draw_circle(int x0, int y0, int radius, uint8_t r, uint8_t g, uint8_t b);

    // 绘制矩形边框
    void draw_rect(int x, int y, int w, int h, uint8_t r, uint8_t g, uint8_t b);

    // 填充矩形
    void fill_rect(int x, int y, int w, int h, uint8_t r, uint8_t g, uint8_t b);

    // 圆角矩形
    void draw_rounded_rect(int x, int y, int w, int h, int radius,
                           uint8_t r, uint8_t g, uint8_t b);

    // 渐变填充矩形
    void fill_rect_gradient(int x, int y, int w, int h,
                            uint8_t r1, uint8_t g1, uint8_t b1,
                            uint8_t r2, uint8_t g2, uint8_t b2,
                            bool horizontal = true);

    // 带边框的填充矩形
    void fill_rect_with_border(int x, int y, int w, int h,
                               uint8_t fill_r, uint8_t fill_g, uint8_t fill_b,
                               uint8_t border_r, uint8_t border_g, uint8_t border_b,
                               int border_width = 1);
};


#endif //FRAMEBUFFER_H
